package io.github.biezhi.elves.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSONObject;

import io.github.biezhi.elves.common.Constants;
import io.github.biezhi.elves.ok.http.FastHttpClient;
import io.github.biezhi.elves.selenium.QccSelenium;

public class HttpUtil {
	public static String post(String requestUrl, String accessToken, String params)
            throws Exception {
        String contentType = "application/x-www-form-urlencoded";
        return HttpUtil.post(requestUrl, accessToken, contentType, params);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params)
            throws Exception {
        String encoding = "UTF-8";
        if (requestUrl.contains("nlp")) {
            encoding = "GBK";
        }
        return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
            throws Exception {
        String url = requestUrl + "?access_token=" + accessToken;
        return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
    }

    static boolean isProxy = true;
    public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
            throws Exception {
        URL url = new URL(generalUrl);
        // 鎵撳紑鍜孶RL涔嬮棿鐨勮繛鎺?
        String host = "132.122.1.4";
        int port = 9898;
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
//        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        HttpURLConnection connection;
		if(!isProxy){
			connection = (HttpURLConnection) url.openConnection();
		}else{
			connection = (HttpURLConnection) url.openConnection(proxy);
		}
        connection.setRequestMethod("POST");
        // 璁剧疆閫氱敤鐨勮姹傚睘鎬?
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 寰楀埌璇锋眰鐨勮緭鍑烘祦瀵硅薄
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(params.getBytes(encoding));
        out.flush();
        out.close();

        // 寤虹珛瀹為檯鐨勮繛鎺?
        connection.connect();
        // 鑾峰彇鎵€鏈夊搷搴斿ご瀛楁
        Map<String, List<String>> headers = connection.getHeaderFields();
        // 閬嶅巻鎵€鏈夌殑鍝嶅簲澶村瓧娈?
        for (String key : headers.keySet()) {
            System.err.println(key + "--->" + headers.get(key));
        }
        // 瀹氫箟 BufferedReader杈撳叆娴佹潵璇诲彇URL鐨勫搷搴?
        BufferedReader in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), encoding));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        System.err.println("result:" + result);
        return result;
    }
    
    
    /**
	 * 返回响应url内容
	 * 
	 * @param isProxy
	 * @param requestUrl
	 * @param headerMap
	 * @return
	 */
	public static String getPostHttpReponseBody(boolean isProxy,String requestUrl,Map<String, Object> headerMap){
		String jsonStr = "";
		try {
			String headerKey = "Content-Type";
			String headerValue = "application/x-www-form-urlencoded";
			if(headerMap!=null && headerMap.size() > 0) {
				if(headerMap.containsKey("headerKey")) {
					headerKey = StringUtils.getValueForKey("headerKey", headerMap);
				}
				if(headerMap.containsKey("headerValue")) {
					headerValue = StringUtils.getValueForKey("headerValue", headerMap);
				}
			}
			io.github.biezhi.elves.ok.http.Response okHttpResponse;
			if(!isProxy){
				okHttpResponse = FastHttpClient
						.post()
						.addHeader(headerKey, headerValue)
						.url(requestUrl)
						.build()
						.execute();
			}else{
				Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(Constants.PROXY_IP, Constants.PROXY_PORT));
				okHttpResponse = FastHttpClient
						.newBuilder()
						.proxy(proxy)
						.build()
						.post()
						.addHeader(headerKey, headerValue)
						.url(requestUrl)
						.build()
						.execute();
			}
			jsonStr = okHttpResponse.string();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonStr;
	}
	
	/**
	 * 返回响应url内容(企查查专用)
	 * 
	 * @return
	 */
	public static String getQccGetHttpReponseBody(String requestUrl){
		String jsonStr = "";
		try {
			System.out.println("获取url内容时，先休眠5000毫秒......");
			Thread.sleep(5000);
			System.out.println("已休眠5000毫秒，开始获取url内容===>");
			String qccCookie = QccSelenium.reloadQccCookie(requestUrl);
			io.github.biezhi.elves.ok.http.Response okHttpResponse;
			if(!Constants.IS_PROXY){
				okHttpResponse = FastHttpClient
						.get()
						.addHeader("cookie", qccCookie)
						.url(requestUrl)
						.build()
						.execute();
			}else{
				Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(Constants.PROXY_IP, Constants.PROXY_PORT));
				okHttpResponse = FastHttpClient
						.newBuilder()
						.proxy(proxy)
						.build()
						.get().addHeader("cookie", qccCookie)
						.url(requestUrl)
						.build()
						.execute();
			}
			jsonStr = okHttpResponse.string();
			if("[]".equals(jsonStr)){
				jsonStr = "";
			}
			//判断是否为json格式
			boolean isJson = StringUtils.isJsonFormat(jsonStr);
			if(!isJson){
				String scriptRequestUrl = requestUrl.replace("http://www.qichacha.com/", "http://www.qichacha.com/index_verify?type=companysearch&back=/");
				String scriptStr = "<script>window.location.href='" + scriptRequestUrl +"';</script>";
				
				if(scriptStr.equals(jsonStr)){
//					System.out.println("过于频繁调用企查查，超出企查查询次数，暂时休眠，需人工干预，休眠10000毫秒......");
//					Thread.sleep(10000);
					Constants.QCC_PAQU_STATE = "1";
					jsonStr = getQccGetHttpReponseBody(scriptRequestUrl);
				}else{
					if(StringUtils.isNullOrEmpty(jsonStr)){
						Constants.QCC_PAQU_STATE = "2";
						jsonStr = getQccGetHttpReponseBody(scriptRequestUrl);
					}else{
						Document doc = Jsoup.parse(jsonStr);
						Elements normalLoginElements = doc.select("#normalLoginPanel");
						if((normalLoginElements!=null && normalLoginElements.size()>0)){
							Constants.QCC_PAQU_STATE = "2";
							jsonStr = getQccGetHttpReponseBody(requestUrl);
						}
					}
				}
			}
		} catch (SocketTimeoutException e) {
			System.err.println("io.github.biezhi.elves.spider.getHttpReponseBody，SocketTimeoutException，返回响应url内容，链接串为:" + requestUrl + "{{}}==>" + StringUtils.getErrorInfoFromException(e));
			
			if(Constants.IS_PROXY){
				System.out.println("io.github.biezhi.elves.spider.getHttpReponseBody，网络超时，休眠5000毫秒后，重新再调用......");
				try {
					Thread.sleep(5000);
					System.out.println("io.github.biezhi.elves.spider.getHttpReponseBody，已休眠5000毫秒，开始重新再调用getHttpReponseBody方法===>");
					Constants.QCC_PAQU_STATE = "2";
					getQccGetHttpReponseBody(requestUrl);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
		} catch (Exception e) {
			System.err.println("io.github.biezhi.elves.spider.getHttpReponseBody，返回响应url内容，链接串为:" + requestUrl + "{{}}==>" + StringUtils.getErrorInfoFromException(e));
			
			System.out.println("io.github.biezhi.elves.spider.getHttpReponseBody，休眠5000毫秒后，重新再调用......");
			try {
				Thread.sleep(5000);
				System.out.println("io.github.biezhi.elves.spider.getHttpReponseBody，已休眠5000毫秒，开始重新再调用getHttpReponseBody方法===>");
				getQccGetHttpReponseBody(requestUrl);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
		return jsonStr;
	}
}